#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QTimer>
#include <QFileDialog>
#include <QDesktopServices>
#include <QMessageBox>
#include <QTextStream>
#include <QProcess>
#include <QTemporaryFile>
#include <QDebug>

#include <QMovie>
#define ROWTEMPLATE "\n\
            <tr>\n\
              <td class=\"info\" width=\"150\"><strong>%0</strong></td>\n\
              <td>%1</td>\n\
            </tr>%2"

#define SECTIONTEMPLATE "\n\
    <h2>%0</h2>\n\
    <table cellpadding=\"5\" width=\"100%\">\n\
    __SECTIONROWTEMPLATE__\
    </table>\n\
    __SECTIONTEMPLATE__"


MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow),
    qfd(new QFileDialog),
    sectionstr(SECTIONTEMPLATE),
    rowstr(ROWTEMPLATE),
    find(new QProcess)
{
    ui->setupUi(this);
    QMovie* mov=new QMovie("://progress_indicator_1.gif");
    ui->label->setMovie(mov);
    ui->label->setGeometry(QRect(0,0,32,32));
    mov->start();

//    connect(qfd, SIGNAL(accepted()), SLOT(TraverseSDKDir()));
    QFile htmlfile("://Qt_sdkinfo.html");
    htmlfile.open(QIODevice::ReadOnly);
    html = htmlfile.readAll();

    QTimer::singleShot(100, this, SLOT(RootDirPicker()));
    platformIdentifier["Symbian1"] = "Symbian S60 3rd/5th";
    platformIdentifier["Symbian3"] = "Symbian^3";
    platformIdentifier["Desktop"] = "Desktop";
    platformIdentifier["Simulator"] = "Simulator";
    platformIdentifier["Madde"] = "MeeGo 1.2 Harmattan";
    platformIdentifier["Maemo5"] = "Maemo 5";

//    targetdirs["Desktop"]
}

MainWindow::~MainWindow()
{
    delete qfd;
    delete ui;
}

//void MainWindow::addToTemplate(QString key, QString value)
//{
//    html = html.replace("__ROWTEMPLATE__", rowstr.arg(key).arg(value).arg("__ROWTEMPLATE__"));
////    rawpairs.append(qMakePair(key, value));

//    QTextBrowser tb;
//    tb.setHtml(value);
////    out << key << ": " << tb.toPlainText() << endl;
//}

void MainWindow::addToTemplate(QList<QPair<QString, QString> > list)
{
    bool insection = false;
    for (int i = 0; i < list.length(); i++)
    {
        QPair<QString, QString> key = list.at(i);
//        rawpairs.append(key);
        if (key.first == "section") {
            insection = true;
            html = html.replace("__SECTIONROWTEMPLATE__", ""); // close off any previous open sections we might have
            html = html.replace("__SECTIONTEMPLATE__", sectionstr.arg(key.second));
//            out << endl << key.second << endl << endl;
        } else {
            if (insection) {
                html = html.replace("__SECTIONROWTEMPLATE__", rowstr.arg(key.first).arg(key.second).arg("__SECTIONROWTEMPLATE__"));
            } else {
                html = html.replace("__ROWTEMPLATE__", rowstr.arg(key.first).arg(key.second).arg("__ROWTEMPLATE__"));
            }
//            out << " " << key.first << ": " << key.second << endl;
        }
    }
    html = html.replace("__SECTIONROWTEMPLATE__", ""); // close off any previous open sections we might have
    QString temphtml = html;
    temphtml.replace("__SECTIONTEMPLATE__","");
    ui->textBrowser->setHtml(temphtml);
//    QTextBrowser tb;
//    tb.setHtml(value);
//    out << endl;
}

void MainWindow::processTarget()
{
    QString qmakepath = find->readLine().trimmed();
    qDebug() << qmakepath;
    if (!qmakepath.isEmpty()) {
        qmake = new QProcess();
        qmake->start(qmakepath, QStringList() << "-query" << "QMAKE_MKSPECS");
        qmake->waitForFinished(10000);
        QString mkspecpath = qmake->readAllStandardOutput().trimmed();
        qDebug() << mkspecpath;
        delete qmake;

        QTemporaryFile qtf;
        qtf.open();
        QFile proFile("://info.pro");
        proFile.open(QIODevice::ReadOnly);
        qtf.write(proFile.readAll());
        qtf.close();
        qmake = new QProcess();
        QProcessEnvironment env = QProcessEnvironment::systemEnvironment();
        env.insert("QMAKESPEC", mkspecpath + "/default"); // Add an environment variable
        qmake->setProcessEnvironment(env);
        qmake->start(qmakepath, QStringList() << qtf.fileName());
    //    qmake->start(qmakepath.filePath(), QStringList() << qtf.fileName());
        qDebug() << proFile.size() << qtf.fileName() << qtf.size();
        qmake->waitForFinished(10000);

        QString output = qmake->readAllStandardError();
        QStringList outlines = output.split("\n");
        outlines.replaceInStrings("Project MESSAGE: ","");
        outlines.replaceInStrings("\r","");
        qDebug() << outlines;
        delete qmake;
        if (output.startsWith("Project MESSAGE: TARGET")) {
            QList<QPair<QString, QString> > list;
            list.append(QPair<QString,QString>("section", output.mid(24,output.indexOf("\n")-24) + " target"));
            foreach (QString line, outlines)
            {
                if (!line.startsWith("WARNING") &&!line.startsWith("TARGET") && line.indexOf(":")>0)
                    list.append(QPair<QString,QString>(line.left(line.indexOf(":")), line.right(line.size()-1-line.indexOf(":")) ));

            }
            addToTemplate(list);
        }
    }
    ui->progressBar->setValue(ui->progressBar->value()+1); // yes, I made this up
    if (find->bytesAvailable())
        processTarget();
}

void MainWindow::hideProgress()
{
    ui->progressBar->hide();
    ui->label->hide();
}

void MainWindow::TraverseSDKDir()
{
    if (qfd->directory().exists() && QFile::exists(qfd->directory().absolutePath() + "/components.xml")) {
        connect(find, SIGNAL(readyRead()), SLOT(processTarget()));
        connect(find, SIGNAL(finished(int)), SLOT(hideProgress()));
        QProcess qtc;
#if defined(Q_WS_X11)
        find->start("find", QStringList() << qfd->directory().absolutePath() << "-name" << "qmake");
        qtc.start(qfd->directory().absolutePath() + "/QtCreator/bin/qtcreator", QStringList() << "-version");
#elif defined(Q_WS_MAC)
        find->start("find", QStringList() << qfd->directory().absolutePath() << "-name" << "qmake");
        qtc.start(qfd->directory().absolutePath() + "/Qt Creator.app", QStringList() << "-version");
#elif defined( Q_WS_WIN )
        QDir::setCurrent(qfd->directory().absolutePath());
        find->start("cmd.exe", QStringList() << "/k" << "dir" << "/s" << "/b" << "qmake.exe");
        qtc.start(qfd->directory().absolutePath() + "\\QtCreator\\bin\\qtcreator.exe", QStringList() << "-version");
#endif
        ui->progressBar->setMaximum(30); // yes, I made this up
        ui->progressBar->setValue(1); // yes, I made this up
        qtc.waitForFinished(10000);

        QString qtcoutput = qtc.readAllStandardError();
        QString plugins;
        QList<QPair<QString, QString> > list;
        QStringList qtcoutlines = qtcoutput.split("\n");

        qtcoutlines.replaceInStrings("\r","");
        foreach (QString line, qtcoutlines)
        {
            if (line.startsWith("Qt Creator")) {
                QStringList qsl = line.split(" ");
                list.append(QPair<QString,QString>("section", "QtCreator"));
                list.append(QPair<QString,QString>("QTCREATOR", qsl.at(2)));
            } else if (line.startsWith("  ")) { // look ! a plugin !
                plugins += line.trimmed().split(" ").at(0) + ", " ;
            }
        }
        if (!plugins.isEmpty())
            list.append(QPair<QString,QString>("PLUGINS", plugins));

        addToTemplate(list);

    } else
        QMessageBox::critical(this, tr("QtSDK not found"), tr("Uh oh - does not seem to be a QtSDK install"));
}

void MainWindow::RootDirPicker()
{
    qfd->setFileMode(QFileDialog::DirectoryOnly);
    qfd->setViewMode(QFileDialog::List);

    // try and (pre)set the directory for default install paths
#if defined(Q_WS_X11) || defined(Q_WS_MAC)
    qfd->setDirectory(QDesktopServices::storageLocation(QDesktopServices::HomeLocation) + "/QtSDK/");
#elif defined( Q_WS_WIN )
    qfd->setDirectory("C:\\QtSDK\\");
#endif
    QDir defaultdir(qfd->directory());
    qfd->setWindowTitle(tr("Select SDK install directory"));
    if (!defaultdir.exists() || QMessageBox::question(this, tr("SDK Location confirmation"), QString(tr("Use default SDK install directory ?\n(%0)")).arg(defaultdir.absolutePath()), QMessageBox::Ok | QMessageBox::No) == QMessageBox::No)
        qfd->exec();
    TraverseSDKDir();
}
